# -*- coding: utf-8 -*-
# @Time : 2022/7/24 14:44
# @Author : WangYunfei
# @FileName: 登录.py
# @Email: lxb_wyf@163.com
"""
https://36kr.com/information/travel/
rsa 加密 非对称加密
"""
import base64
import time

import execjs
import requests
import rsa


class KR(object):

    def __init__(self):
        self.url = "https://gateway.36kr.com/api/mus/login/byMobilePassword"
        self.headers = {
            'Connection': 'close',
            "accept": "*/*",
            "accept-encoding": "gzip, deflate, br",
            "accept-language": "zh-CN,zh;q=0.9",
            "content-type": "application/json",
            "cookie": "sajssdk_2015_cross_new_user=1; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%221822eedc1c8a5-0d24ed161c7e57-26021a51-1382400-1822eedc1c9324%22%2C%22%24device_id%22%3A%221822eedc1c8a5-0d24ed161c7e57-26021a51-1382400-1822eedc1c9324%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E8%87%AA%E7%84%B6%E6%90%9C%E7%B4%A2%E6%B5%81%E9%87%8F%22%2C%22%24latest_referrer%22%3A%22https%3A%2F%2Fwww.baidu.com%2Flink%22%2C%22%24latest_referrer_host%22%3A%22www.baidu.com%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC%22%7D%7D; acw_tc=2760824f16586447607354070e56aeb1496aac27a720a2fd738932879dcef8",
            "origin": "https://36kr.com",
            "referer": "https://36kr.com/",
            "sec-ch-ua": "\".Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"103\", \"Chromium\";v=\"103\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-site",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"
        }

        self.pu_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCeiLxP4ZavN8qhI+x+whAiFpGWpY9y1AHSQC86qEMBVnmqC8vdZAfxxuQWeQaeMWG07lXhXegTjZ5wn9pHnjg15wbjRGSTfwuZxSFW6sS3GYlrg40ckqAagzIjkE+5OLPsdjVYQyhLfKxj/79oOfjl/lV3rQnk/SSczHW0PEyUbQIDAQAB"
        """
        -----BEGIN PUBLIC KEY-----
        MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCeiLxP4ZavN8qhI+x+whAiFpGWpY9y1AHSQC86qEMBVnmqC8vdZAfxxuQWeQaeMWG07lXhXegTjZ5wn9pHnjg15wbjRGSTfwuZxSFW6sS3GYlrg40ckqAagzIjkE+5OLPsdjVYQyhLfKxj/79oOfjl/lV3rQnk/SSczHW0PEyUbQIDAQAB
        -----END PUBLIC KEY-----
        """

    def spider(self, mobile, password):
        _data = {
            "krtoken": "",
            "partner_id": "web",
            "timestamp": time.time(),
            "param": {
                "countryCode": "86",
                "mobileNo": self.js_encrypt(self.pu_key, mobile),
                "password": self.rsa_encrypt(self.pu_key, password)
            }
        }
        res = requests.post(url=self.url, json=_data, headers=self.headers)
        print(res.status_code)
        print(res.text)

    def rsa_encrypt(self, pu_key_str, value):
        # 公钥加密
        _key = self._str2key(pu_key_str)
        modulus = int(_key[0], 16)
        exponent = int(_key[1], 16)
        pubkey = rsa.PublicKey(modulus, exponent)
        rsa_en = rsa.encrypt(value.encode("utf-8"), pubkey)
        return base64.b64encode(rsa_en).decode()

    @staticmethod
    def _str2key(s):
        # 对字符串解码
        b_str = base64.b64decode(s)

        if len(b_str) < 162:
            return False

        hex_str = ''

        # 按位转换成16进制
        for x in b_str:
            h = hex(x)[2:]
            h = h.rjust(2, '0')
            hex_str += h

        # 找到模数和指数的开头结束位置
        m_start = 29 * 2
        e_start = 159 * 2
        m_len = 128 * 2
        e_len = 3 * 2

        modulus = hex_str[m_start:m_start + m_len]
        exponent = hex_str[e_start:e_start + e_len]

        return modulus, exponent

    @staticmethod
    def js_encrypt(pubkey, key):
        js_str = """
        window = global;
        JSEncrypt = require('jsencrypt')
        a = function(i, e) {
                var r = new JSEncrypt;
                r.setPublicKey(i);
                var a = r.encrypt(e);
                return a
        }
        """
        context = execjs.compile(js_str)
        params = context.call("a", pubkey, key)
        return params


if __name__ == '__main__':
    kr = KR()
    print(kr.rsa_encrypt(kr.pu_key, "a1"))
    print(kr.js_encrypt(kr.pu_key, "a1"))
    kr.spider("17739569679", "123456789")
